package org.n.shop.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static org.n.shop.config.TokenConfig.EXPIRE_DATE;
import static org.n.shop.config.TokenConfig.TOKEN_SECRET;

public class TokenUtil {
    public static String token(String username, String password) {
        String token = "";

        Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
        Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        Map<String, Object> header = new HashMap<>();
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        token = JWT.create()
                .withHeader(header)
                .withClaim("username", username)
                .withClaim("password", password)
                .withExpiresAt(date)
                .sign(algorithm);

        return token;
    }

    public static boolean verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
